let express=require(`express`)
let router=express.Router()
let db=require(`./4.封装函数db`)
let jwk=require(`jsonwebtoken`)
router.post(`/a/b/login`,(req,res)=>{
    let {username,password}=req.body
    // console.log(req.body)
db(`SELECT * FROM users WHERE username='${username}' AND password='${password}';`,(err,arr)=>{
    console.log(arr)
    if(err||arr.length===0){
        res.send({code:400,msg:`账号或密码错误`})
    }else{
    let token=jwk.sign({id:arr[0].id},`hehe`,{expiresIn:'1h'})
    console.log(token)
        res.send({code:200,msg:`登录成功`,token:'Bearer '+token})
    }
})
})

router.get(`/a/b/user`,(req,res)=>{
    let {id}=req.user
    db(`select nickname ,userPic from users where id=${id}`,(err,arr)=>{
        console.log(arr)
        // if(err) return console.log(``)
        res.send({code:200,msg:`获取成功`,data:arr})
    })
})


router.get(`/a/b/details`,(req,res)=>{
    let{id}=req.user
    db(`select * from users where id=${id}`,(err,arr)=>{
        console.log(arr)
        res.send({code:200,msg:`获取成功`,data:arr})
    })
})
let multer =require(`multer`)
let upload=multer({dest:`uploads/`})
router.post(`/a/b/useredit`,upload.single('userPic'),(req,res)=>{
    // console.log(req.file)
    // let pic
    console.log(12)
    let {filename}=req.file
    let {id}=req.user
    let {username,nickname,email,password}=req.body
    console.log(username,nickname,email,password)
    db(`update users set username='${username}',nickname='${nickname}',email='${email}',password=${password},userPic='${filename}'  where id=${id};`,(err,result)=>{
        if(err||result.affectedRows===0)  res.send({code:2000,msg:`错误`})
        res.send({code:200,msg:result})
    })
})
module.exports=router